After we have tinkered with general plotting in base R, and before we learn about alternative plotting methods using ggplot2, we want to use this exercise to programmatically play with some base R plots. In the previous exercise, we had some repeated tasks to perform. Maybe we can find a more elegant way of creating multiple plots.

Make sure our GESIS Panel COVID-19 survey data are loaded:

library(dplyr)
library(haven)

gp_covid <- 
  read_sav(
    "../data/ZA5667_v1-1-0.sav"
  ) %>% 
  sjlabelled::set_na(na = c(-1:-99, 97))

1

Write a function that automatically creates a table of an input variable and feeds it into a barplot. Moreover, provide an interface to enter the variable name as a character string and the dataset separately by including two commands in the function call.
After the function call, use two function arguments with function (variable, data) and call the variable within the function with data[[variable]].

Alas, that was not about plotting but rather about programming (sorry!). But now you can use this function and include it in a loop to actually plot stuff!

2

Take all four variables from the previous exercise session and feed them in a loop that calls the plotting function. You may want again call par() before the loop to have all variables nicely plotted in one graph.
Define a character vector with the variable names before you build your graph. For the loop, I’d suggest using a for() loop, which iterates over this character vector.

Before we later start with the other exercises, you may want to consider to clean your graphics device with dev.off()

dev.off()
## null device 
##           1